package cn.hinglo.business.service;

import cn.hinglo.business.model.UserInfo;
import cn.hinglo.common.util.SysCommonKit;
import cn.hinglo.permission.service.UploadService;
import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.upload.UploadFile;

import java.util.Map;

/***
 * @author HingLo.C
 * @description: 用户管理服务层
 */
public class UserInfoService {
    @Inject
    private UploadService uploadService;


    /***
     * 用户管理
     * @param page 页码
     * @param size 大小
     * @return
     */
    public Map<String, ?> listService(Integer page, Integer size) {
        SqlPara sql = Db.getSqlPara("userInfo.list");
        Page<Record> list = Db.paginate(page, size, sql);
        return SysCommonKit.pageKit(list.getTotalRow(), list.getList());
    }

    /***
     * 获取用户信息
     * @param id 用户主键
     * @return 返回信息
     */
    public Record getUserService(Integer id) {
        return Db.findFirst(Db.getSql("userInfo.getUser"), id);
    }

    /***
     * 返回指定字段信息
     * @param id 用户ID
     * @return 返回结果
     */
    public Record getUserFieldService(Integer id) {
        Record first = Db.findFirst(Db.getSql("userInfo.getUser"), id);
        Record res = new Record();
        String[] having = {"avatar", "id", "name", "username"};
        for (String s : having) {
            res.set(s, first.get(s));
        }
        return res;
    }

    /***
     * 获取用户信息
     * @param id 用户主键
     * @return 返回信息
     */
    public boolean updateModifyService(Long id, Integer modify) {
        return Db.update(Db.getSql("userInfo.updateModify"), modify, id) == 1;
    }

    /***
     * 获取用户信息
     * @return 返回信息
     */
    public boolean updateUserInfoService(UserInfo userInfo) {
        return userInfo.update();
    }

    /***
     * 头像跟换
     * @param userId 用户编号
     * @param img 头像地址
     * @return 返回地址
     */
    public String changeAvatarService(Integer userId, UploadFile img) {
        String avatar = uploadService.imgUploadService(img, "avatar");
        Db.update(Db.getSql("userInfo.changeAvatar"), avatar, userId);
        return avatar;
    }

}
